/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sychip.fhc.app.todo

import android.widget.Toast
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.fhc.base.EventObserver
import com.fhc.base.FhcFlowEventBus
import com.fhc.base.FlowEventBusData
import com.fhc.view.BottomBarBox
import com.fhc.view.StatusBarBox
import com.sychip.fhc.app.drawer.nav.DrawerItem
import com.sychip.fhc.app.drawer.nav.DrawerNavHost
import com.sychip.fhc.app.todo.nav.tab.MainTabNavHost
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.system.exitProcess


fun NavGraphBuilder.startComposable(
    navController: NavHostController,
    onGotoMainDrawer: () -> Unit,
    onGotoMainTab: () -> Unit
){
    composable(TodoDestinations.START_ROUTE) {entry ->
        Surface {
            Column {
                StatusBarBox(0)
                Column(
                    modifier = Modifier.weight(1f).fillMaxSize()
                ) {
                    StartScreen(
                        onGotoMainDrawer = {
                            onGotoMainDrawer()
                        },
                        onGotoMainTab ={
                            onGotoMainTab()
                        },
                    )
                }
                BottomBarBox(0)
            }
        }
    }
}

fun NavGraphBuilder.mainDrawerNavGraph(){
    var pressedTime: Long = 0
    composable(DrawerItem.TASKS.route) { entry ->
        val  aa = LocalContext.current
        Surface {
            Column {
                Column(
                    modifier = Modifier.weight(1f).fillMaxSize()
                ) {
                    DrawerNavHost(
                        showCover = false,
                        onBack={
//                            navActions.navigateToStart()
                            if (pressedTime + 2000 > System.currentTimeMillis()) {
                                exitProcess(0)
                            } else {
                                Toast.makeText(aa, R.string.pressBackExit, Toast.LENGTH_SHORT).show()
                            }
                            pressedTime = System.currentTimeMillis();
                        }
                    )
                }
//                BottomBarBox()
            }
        }

    }
}

fun NavGraphBuilder.mainTabNavGraph(){
    var pressedTime: Long = 0
    composable(TodoDestinations.MAIN_TAB_ROUTE) { entry ->
        val  aa = LocalContext.current
        Surface {
            Column {
//                StatusBarBox()  这里是全局tab的，考虑到各个tab可能不同风格，在各自tab内设置
                Column(
                    modifier = Modifier.weight(1f).fillMaxSize()
                ) {
                    MainTabNavHost(
                        onBack={
//                            navActions.navigateToStart()
                            if (pressedTime + 2000 > System.currentTimeMillis()) {
                                exitProcess(0)
                            } else {
                                Toast.makeText(aa, R.string.pressBackExit, Toast.LENGTH_SHORT).show()
                            }
                            pressedTime = System.currentTimeMillis()
                        }
                    )
                }
//                BottomBarBox()
            }
        }

    }
}

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun TodoNavGraph(
    modifier: Modifier = Modifier,
    navController: NavHostController = rememberNavController(),
    startDestination: String = TodoDestinations.START_ROUTE,
    navActions: TodoNavigationActions = remember(navController) {TodoNavigationActions(navController)}
) {
//    val currentNavBackStackEntry by navController.currentBackStackEntryAsState()
//    val currentRoute = currentNavBackStackEntry?.destination?.route ?: startDestination

    NavHost(
        navController = navController,
        startDestination = startDestination,
        enterTransition = {  EnterTransition.None },
        exitTransition = { ExitTransition.None },
        popEnterTransition = {EnterTransition.None },
        popExitTransition = { ExitTransition.None },
        modifier = modifier
    ) {
        startComposable(
            navController = navController,
            onGotoMainDrawer = { navActions.navigateToDrawerMain() },
            onGotoMainTab = { navActions.navigateToMainTab() }
        )

        mainTabNavGraph()
        mainDrawerNavGraph()

    }

    EventObserver(onCreate = {
        CoroutineScope(Dispatchers.Default).launch {
            FhcFlowEventBus.subscribe<FlowEventBusData> {event->
                CoroutineScope(Dispatchers.Main).launch {
                    navActions.navigateToStart()
//                    if(event.dataObj is EventDataTest){
//                        Timber.i("TodoNavGraph  FlowEventBusData=    ${event.dataObj.firstName}  ${event.dataObj.lastName}")
//                    }else if(event.dataObj is EventDataTest2){
//                        Timber.i("TodoNavGraph  FlowEventBusData=    ${event.dataObj.aaa}   ${event.dataObj.bbb}")
//                    }
                }
            }
        }
    })
}
